Events.PlayerEraChanged.Add(function (playerId, eraId)
	local playerConfig = PlayerConfigurations[playerId];
	local civ = playerConfig:GetCivilizationTypeName();
	if ExposedMembers.DLHD.Utils.CivilizationHasTrait(civ, 'TRAIT_CIVILIZATION_MAGICAL_GIRLS') then
		local player = Players[playerId];
		player:AttachModifierByID('CIVIC_GRANT_PLAYER_GOVERNOR_POINTS');
	end
end);

local FREE_TECH_KEY_MAGICA = 'HD_FREE_TECH_MAGICA';
local FREE_CIVIC_KEY_MAGICA = 'HD_FREE_CIVIC_MAGICA';
Events.GovernorPromoted.Add(function (playerId, governorId, promotionId)
	local player = Players[playerId];
	local promotionInfo = GameInfo.GovernorPromotions[promotionId];
	if promotionInfo.GovernorPromotionType == 'GOVERNOR_PROMOTION_CHOBE_ONE' or promotionInfo.GovernorPromotionType == 'GOVERNOR_PROMOTION_CHOBE_FIVE' then
		local techRemains = player:GetProperty(FREE_TECH_KEY_MAGICA) or 0;
		player:SetProperty(FREE_TECH_KEY_MAGICA, techRemains + 1);
		local civicRemains = player:GetProperty(FREE_CIVIC_KEY_MAGICA) or 0;
		player:SetProperty(FREE_CIVIC_KEY_MAGICA, civicRemains + 1);
	end
	if promotionInfo.GovernorPromotionType == 'GOVERNOR_PROMOTION_CHOBE_SIX' then
		local player = Players[playerId];
		for _, city in player:GetCities():Members() do
			city:GetBuildQueue():FinishProgress();
		end
	end
end);
GameEvents.HD_FreeTechSwitchMagica.Add(function (playerId, techId)
	local player = Players[playerId];
	local remains = player:GetProperty(FREE_TECH_KEY_MAGICA) or 0;
	local playerTech = player:GetTechs();
	
	player:SetProperty(FREE_TECH_KEY_MAGICA, remains - 1);
	playerTech:SetResearchProgress(techId, playerTech:GetResearchCost(techId));
end);
GameEvents.HD_FreeCivicSwitchMagica.Add(function (playerId, civicId)
	local player = Players[playerId];
	local remains = player:GetProperty(FREE_CIVIC_KEY_MAGICA) or 0;
	local playerCulture = player:GetCulture();

	player:SetProperty(FREE_CIVIC_KEY_MAGICA, remains - 1);
	playerCulture:SetCulturalProgress(civicId, playerCulture:GetCultureCost(civicId));
end);

local CHUBE_UNESTABLISHED_KEY = 'CHUBE_UNESTABLISHED_TURN_';
GameEvents.ChubeUnestablishedSwitch.Add(function (playerId)
	local player = Players[playerId];
	local turn = Game.GetCurrentGameTurn();
	player:SetProperty(CHUBE_UNESTABLISHED_KEY .. turn, 1);
end);
GameEvents.ChubeCheckSwitch.Add(function (playerId, amount)
	local player = Players[playerId];
	local turn = Game.GetCurrentGameTurn();
	local total = 0;
	for i = 0, 4 do
		if player:GetProperty(CHUBE_UNESTABLISHED_KEY .. (turn - i)) == 1 then
			total = total + 1;
		end
	end
	if total > 2 then
		for _, city in player:GetCities():Members() do
			if amount > 0 then
				CityManager.TransferCityToFreeCities(city);
				amount = amount - 1;
			end
		end
	end
end);